package com.sxhuayuan.parking.controller.member;

import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Validator;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import com.sxhuayuan.parking.compenent.editor.DateEditor;
import com.sxhuayuan.parking.config.Platform;
import com.sxhuayuan.parking.entity.ParkingLot;
import com.sxhuayuan.parking.entity.ParkChannel;
import com.sxhuayuan.parking.exception.SessionTimeoutException;
import com.sxhuayuan.parking.utils.DeviceUtil;
import com.sxhuayuan.parking.utils.SpringUtils;

public class BaseController {

	@Resource(name = "validator")
	private Validator validator;

	private final String ERROR_VIEW_MESSAGE = "error_msg";
	// 微信小程序session_key
	public static final String WX_SESSION_KEY = "wx_session_key";
	protected static final String ERROR_VIEW = "common/error.html";

	protected void addErrorMessage(String msg) {
		RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
		requestAttributes.setAttribute(ERROR_VIEW_MESSAGE, SpringUtils.getMessage(msg), RequestAttributes.SCOPE_REQUEST);
	}

	/**
	 * 数据绑定
	 * 
	 * @param binder
	 *            WebDataBinder
	 */
	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
		binder.registerCustomEditor(Date.class, new DateEditor(true));
	}

	protected Platform getPlatform(HttpServletRequest request) {
		String userAgent = request.getHeader("User-Agent");
		if (DeviceUtil.isFromWeixin(userAgent)) {
			return Platform.weixin;
		} else if (DeviceUtil.isFromAlipay(userAgent)) {
			return Platform.alipay;
		} else
			return null;
	}

	protected String getExitSnFromSession() {
		Object obj = SecurityUtils.getSubject().getSession().getAttribute(ParkChannel.SESSION_ATTR_NAME);
		return obj == null ? null : obj.toString();
	}

	protected String getLotSnFromSession() {
		Object obj = SecurityUtils.getSubject().getSession().getAttribute(ParkingLot.SESSION_ATTR_NAME);
		if (obj == null)
			throw new SessionTimeoutException();
		return obj.toString();
	}

	/**
	 * 缓存值到session
	 * 
	 * @param session
	 * @param key
	 * @param value
	 */
	protected void cacheInSession(HttpSession session, String key, String value) {
		session.setAttribute(key, value);
	}

	/**
	 * 从session中读取
	 * 
	 * @param key
	 * @return
	 */
	protected String readInSession(String key) {
		Object obj = SecurityUtils.getSubject().getSession().getAttribute(WX_SESSION_KEY);
		return obj == null ? null : obj.toString();
	}
}
